package com.lmc.form.script;

import com.free.bsf.core.db.DbHelper;
import com.free.bsf.core.util.ContextUtils;
import com.free.bsf.core.util.LogUtils;
import com.free.bsf.core.util.StringUtils;
import com.free.bsf.redis.RedisProvider;
import com.lmc.form.dao.dal.paas_form_model_dal;
import lombok.val;
import lombok.var;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class DynamicDataSourceScript {
    public static Map run(String form_key, Object custom_json, String dataSourceScripts, String filterLoadOrder){
        Map dataSourceResult = new HashMap<String,Object>();
        val requestJson = new LinkedHashMap();
        requestJson.put("form_key", form_key);
        requestJson.put("custom_json", custom_json);
        val ds = new DataSourceScripts(dataSourceScripts);
        val formInfoStr = "{form_key:'" + form_key + "'}";
        for (val s : ds.filter()) {
            if(filterLoadOrder==null||filterLoadOrder.equals(s.loadOrder)) {
                try {
                    val redis = ContextUtils.getBean(RedisProvider.class,false);
                    val cacheKey = s.name+"_"+s.script.hashCode();
                    Object result = null;
                    if(redis!=null&&s.cacheTime>0)
                    {
                        result = redis.get(cacheKey);
                    }
                    if(result==null)
                    {result = DynamicScript.run(formInfoStr, s.script, requestJson);}
                    if(redis!=null&&s.cacheTime>0)
                    {
                        redis.set(cacheKey,result,s.cacheTime);
                    }
                    dataSourceResult.put(s.name, result);
                } catch (Exception e) {
                    dataSourceResult.put(s.name, null);
                    LogUtils.error(DynamicDataSourceScript.class, "", "动态执行数据源出错:" + StringUtils.nullToEmpty(form_key), e);
                }
            }
        }
        return dataSourceResult;
    }
}
